package com.example.hospital.util;

import cn.hutool.core.util.StrUtil;
import com.example.hospital.constant.UserConstants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)) {
            return true;
        }
        String phoneNumber = JwtHelper.getPhoneNumber(token);
        UserConstants.Role role = JwtHelper.getUserRole(token);
        if (StrUtil.isEmpty(phoneNumber) || role == null) {
            return true;
        }
        UserHolder.saveUser(phoneNumber, role);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除ThreadLocal中的用户信息
        UserHolder.removeUser();
    }
}